package com.wayne.gateway.controller;

import com.wayne.gateway.client.CookieOAuth2Helper;
import com.wayne.gateway.property.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.RequestEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Optional;

/**
 * Create date 2020/8/12.
 *
 * @author evan
 */
@Slf4j
@Controller
public class IndexController {

    @Resource
    private SecurityProperties securityProperties;
    @Autowired
    private NimbusJwtDecoder jwtDecoder;

    @GetMapping("/")
    public String portal(RequestEntity<String> entity) {
        try {
            String value = entity.getHeaders().get("Cookie").get(0);
            Optional<String> accessTokenOptional = Arrays.stream(value.split(";")).filter(cookie -> cookie.trim().startsWith(CookieOAuth2Helper.ACCESS_TOKEN)).findFirst();
            if(accessTokenOptional.isPresent()){
                String accessToken = accessTokenOptional.get().trim().replace(CookieOAuth2Helper.ACCESS_TOKEN + "=", "");
                jwtDecoder.decode(accessToken);
            }
            String loginSuccess = securityProperties.getLoginSuccess();
            if (StringUtils.hasText(loginSuccess)) {
                return "redirect:" + loginSuccess;
            }
        } catch (Exception e) {
            log.warn("解析{}失败: {}", CookieOAuth2Helper.ACCESS_TOKEN,e.getMessage());
        }
        return "redirect:/index";
    }

    @GetMapping("/test")
    public String index(
            Model model,
            @RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
            @AuthenticationPrincipal OAuth2User oauth2User) {
        model.addAttribute("accessToken", authorizedClient.getAccessToken().getTokenValue());
        model.addAttribute("refreshToken", authorizedClient.getRefreshToken().getTokenValue());
        model.addAttribute("userName", oauth2User.getName());
        model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
        model.addAttribute("userAttributes", oauth2User.getAttributes());
        return "index";
    }
}
